<script lang="ts" setup>
import useLoading from '@/hooks/loading'
import { TitleMap } from '@/config/constants'
import { FormInstance } from '@arco-design/web-vue/es/form'
import MyApp from '@/components/MyApp/index.vue'

interface EditProps {
  modelForm: any
  editVisible: boolean
  createData: any
  updateData: any
  setEditVisible: any
  title?: string
  dialogStatus: string
}

const props = withDefaults(defineProps<EditProps>(), {
  editVisible: false,
  modelForm: {
    status: 1,
    order: 0,
    title: '',
  },
  title: '',
  dialogStatus: 'create',
  createData: () => {},
  updateData: () => {},
  setEditVisible: () => {},
})

const { modelForm } = toRefs(props)
const { loading, setLoading } = useLoading()
const formRef = ref<FormInstance>()

const handleClose = () => {
  props.setEditVisible()
  formRef.value!.resetFields()
}

const handleSubmit = () => {
  formRef
    .value!.validate((valid: any) => {
      if (valid) return

      const data = unref(modelForm)
      data.order = parseInt(data.order, 10)
      data.status = typeof data.status !== 'undefined' ? +data.status : 1

      props.dialogStatus === 'create' ? props.createData(data) : props.updateData(data)
      handleClose()
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {
      setLoading(false)
    })
}

const visible = ref(false)
watch(
  () => props.editVisible,
  (show) => {
    visible.value = show
  }
)
</script>
<template>
  <a-modal v-model:visible="visible" @ok="handleSubmit" @cancel="handleClose" draggable :loading="loading">
    <template #title>{{ TitleMap[dialogStatus] }}</template>
    <a-form ref="formRef" :model="modelForm" label-width="50px">
      <a-form-item label="应用" field="appId">
        <MyApp v-model="modelForm.appId" :style="{ width: '100%' }" />
      </a-form-item>
      <a-form-item label="名称" field="name" :rules="[{ required: true, message: '请输入名称' }]" :validate-trigger="['blur']">
        <a-input v-model="modelForm.name" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item label="标题" field="title" :rules="[{ required: true, message: '请输入标题' }]" :validate-trigger="['blur']">
        <a-input v-model="modelForm.title" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="排序" field="order" :validate-trigger="['blur']">
        <a-input v-model="modelForm.order" placeholder="请输入排序" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<style lang="scss"></style>
